package com.zk.qqrobot.util;

import com.zk.qqrobot.util.telnet.JsonResult;
import com.zk.qqrobot.util.telnet.PTUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

public class SSRValidUtil {
    private static final Integer timeout = 500;
    private static final Logger LOGGER = LoggerFactory.getLogger(SSRValidUtil.class);
    public static String valid(String srcSsrs){
        LOGGER.info("数据清洗...");
        Integer suNum = 0;
        StringBuilder builder = new StringBuilder();
        List<String> ssrs = Arrays.asList(srcSsrs.split("ssr://"));

        for (String x:ssrs){
            if (suNum.equals(10)){
                continue;
            }
            try {
                String decoderStr =  new String(Base64.decodeBase64(x),"UTF-8");
                List<String> item = Arrays.asList(decoderStr.split(":"));
                if (item.size() == 1){
                    continue;
                }
                JsonResult jsonResult = PTUtil.telnetResult(item.get(0), Integer.parseInt(item.get(1)), timeout);
                LOGGER.info("telnet=" + jsonResult.getCode());
                if (jsonResult.getCode().equals("200")){
                    builder.append("ssr://").append(x).append("\n");
                    suNum += 1;
                }
            } catch (UnsupportedEncodingException e) {
            }
        }
        LOGGER.info("ssrs size=" +  (ssrs.size() - 1));
        LOGGER.info("OK num=" + suNum);
        LOGGER.info(builder.toString());
        return builder.toString();
    }
}
